mod app;
mod ui;

use anyhow::Result;
use crossterm::event::{self, Event, KeyCode, KeyEventKind};
use crossterm::terminal::{
    disable_raw_mode, enable_raw_mode, EnterAlternateScreen,
    LeaveAlternateScreen,
};
use crossterm::ExecutableCommand;
use ratatui::prelude::*;
use std::io::stdout;
use std::time::Duration;
use local_ip_address::local_ip;
use ipnetwork::IpNetwork;
use log::info;

#[cfg(feature = "logging")]
use env_logger::{Builder, Target};
#[cfg(feature = "logging")]
use std::fs::OpenOptions;

fn main() -> Result<()> {
    // 初始化日志
    #[cfg(feature = "logging")]
    {
        let log_file = OpenOptions::new()
            .create(true)
            .append(true)
            .open("ipp.log")?;
        
        Builder::new()
            .target(Target::Pipe(Box::new(log_file)))
            .filter_level(log::LevelFilter::Debug)
            .init();

        info!("Starting application");
    }

    // 初始化终端
    enable_raw_mode()?;
    stdout().execute(EnterAlternateScreen)?;
    let mut terminal = Terminal::new(CrosstermBackend::new(stdout()))?;

    // 初始化应用
    let ip = local_ip()?;
    let network = IpNetwork::new(ip, 24)?;
    let mut app = app::App::new(network);

    // 主循环
    loop {
        // 处理状态更新
        app.update();

        // 渲染 UI
        terminal.draw(|frame| {
            ui::render(frame, &app);
        })?;

        // 处理输入
        if event::poll(Duration::from_millis(100))? {
            if let Event::Key(key) = event::read()? {
                if key.kind == KeyEventKind::Press {
                    match key.code {
                        KeyCode::Enter => {
                            if let Some(app::Command::Quit) = app.handle_command()? {
                                break;
                            }
                        }
                        KeyCode::Backspace => {
                            app.input.pop();
                        }
                        KeyCode::Up => {
                            app.scroll_message_up();
                        }
                        KeyCode::Down => {
                            app.scroll_message_down();
                        }
                        KeyCode::Char(c) => {
                            match c {
                                'j' => app.scroll_message_down(),
                                'k' => app.scroll_message_up(),
                                _ => app.input.push(c),
                            }
                        }
                        _ => {}
                    }
                }
            }
        }
    }

    // 清理终端
    disable_raw_mode()?;
    stdout().execute(LeaveAlternateScreen)?;
    Ok(())
}